package com.grant.HelloWorld.server;

import java.io.IOException;
import java.io.StringBufferInputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.tools.ant.filters.StringInputStream;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

public class DownloadFileServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -482412590146447924L;
	private static final int BUFSIZE = 20*1024;

	public void doPost(HttpServletRequest req, HttpServletResponse resp){
	
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		String fileKey = req.getParameter("fileKey");
		System.out.println("fileKey="+fileKey);
		try {
			doDownload(req,resp,fileKey);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Sends a file to the ServletResponse output stream. Typically you want the
	 * browser to receive a different name than the name the file has been saved
	 * in your local database, since your local names need to be unique.
	 * 
	 * @param req
	 *            The request
	 * @param resp
	 *            The response
	 * @param filename
	 *            The name of the file you want to download.
	 * @param original_filename
	 *            The name the browser should receive.
	 * @throws IOException 
	 */
	private void doDownload(HttpServletRequest req, HttpServletResponse resp,
			String fileKey) throws IOException {
		//File f = new File(filename);
		String s = getFile(fileKey);
		int length = 0;
		ServletOutputStream op;

		op = resp.getOutputStream();

		ServletContext context = getServletConfig().getServletContext();
		String mimetype = null ; //context.getMimeType(filename);

		//
		// Set the response and go!
		//
		//
		resp.setContentType((mimetype != null) ? mimetype
				: "application/octet-stream");
		resp.setContentLength((int) s.length());
		String original_filename = fileKey;
		resp.setHeader("Content-Disposition", "attachment; filename=\""
				+ original_filename + "\"");

		//
		// Stream to the requester.
		//
		
		byte[] bbuf = new byte[BUFSIZE];
		//DataInputStream in = new DataInputStream(new FileInputStream(f));
		@SuppressWarnings("deprecation")
		StringBufferInputStream in = new StringBufferInputStream(s);
		while ((in != null) && ((length = in.read(bbuf)) != -1)) {
			op.write(bbuf, 0, length);
		}

		in.close();
		op.flush();
		op.close();
	}
	
	private String getFile(String fileKey) {
		String s = "";
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		// Key uploadFileKey = KeyFactory.createKey("Guestbook", guestbookName);
		// Run an ancestor query to ensure we see the most up-to-date
		// view of the Greetings belonging to the selected Guestbook.
		Key downLoadFileKey = KeyFactory.stringToKey(fileKey);
		Entity oneFile = null;
		try {
			oneFile = datastore.get(downLoadFileKey);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (oneFile != null) {

			s = ((Text)oneFile.getProperty("content")).getValue();

		}
		return s;
	}

}
